<?php

namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path'), EXT);

use app\admin\Controller;
use think\Db;
use think\Config;
use think\Paginator;
use think\Request;
use think\Validate;

//require_once EXTEND_PATH.'newMfw-sdk'.DS.'Openapi.php';
header('Content-type:text/html; charset=utf-8');

class Order extends Controller
{
    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];


    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        $data = input();
        $url = '/admin/order/index_html';
        if ($data) {
            foreach ($data as $dk => $dv) {
                if ($dk == $url) {
                    unset($data[$dk]);
                }
                if (!empty($dv)) {
                    $searchData[$dk] = $dv;
                }
            }
            $searchData['search'] = 'all';
        } else {
            $searchData['search'] = 'all';
        }
        if ($this::$isdelete) {
            $map['o.isdelete'] = 1;
        } else {
            $map['o.isdelete'] = 0;
        }
        if ($data['id']) {
            $map['o.id'] = $data['id'];
        }
        if ($data['order_id']) {
            $map['o.order_id'] = array('like', "%{$data['order_id']}%");
        }
        if ($data['uid']) {
            $map['o.uid'] = $data['uid'];
        }
        if ($data['booking_people_name']) {
            $map['o.booking_people_name'] = array('like', "%{$data['booking_people_name']}%");
        }
        if ($data['booking_people_phone']) {
            $map['o.booking_people_phone'] = array('like', "%{$data['booking_people_phone']}%");
        }
        if ($data['sku_name']) {
            $map['o.sku_name'] = array('like', "%{$data['sku_name']}%");
        }
        if ($data['sales_id']) {
            $map['o.sales_id'] = $data['sales_id'];
        }
        if ($data['car_form']) {
            $map['o.car_form'] = $data['car_form'];
        }
        if ($data['product_type']) {
            $map['o.product_type'] = $data['product_type'];
        }
        if ($data['sales_name']) {
            $map['o.sales_name'] = array('like', "%{$data['sales_name']}%");
        }
        if ($data['ota_sales_name']) {
            $map['o.ota_sales_name'] = array('like', "%{$data['ota_sales_name']}%");
        }
        if ($data['remark']) {
            $map['o.remark'] = ['like', '%' . $data['remark'] . '%'];
        }

        if ($data['color']) {
            if ($data['color'] == '10') {
                $map['o.color'] = ['in', '0,10'];
            } else {
                $map['o.color'] = $data['color'];
            }
        }

        if ($data['order_status']) {
            $map['o.order_status'] = $data['order_status'];
        }
        if ($data['isrefund'] == '0' || $data['isrefund']) {
            $map['o.isrefund'] = $data['isrefund'];
        }
        if ($data['platform']) {
            $map['o.platform'] = $data['platform'];
        }
        if ($data['date1'] && $data['date2']) {
            $map['o.start_time'] = array("between", [strtotime($data['date1'] . " 00:00:00"), strtotime($data['date2'] . " 23:59:59")]);
        } else {
            if ($data['date1']) {
                $map['o.start_time'] = array("between", [strtotime($data['date1'] . " 00:00:00"), strtotime($data['date1'] . " 23:59:59")]);
            }
            if ($data['date2']) {
                $map['o.start_time'] = array("between", [strtotime($data['date2'] . " 00:00:00"), strtotime($data['date2'] . " 23:59:59")]);
            }
        }
        if ($data['ctime'] && $data['ctime2']) {
            $map['o.ctime'] = array("between", [strtotime($data['ctime'] . " 00:00:00"), strtotime($data['ctime2'] . " 23:59:59")]);
        } else {
            if ($data['ctime']) {
                $map['o.ctime'] = array("between", [strtotime($data['ctime'] . " 00:00:00"), strtotime($data['ctime'] . " 23:59:59")]);
            }
            if ($data['ctime2']) {
                $map['o.ctime'] = array("between", [strtotime($data['ctime2'] . " 00:00:00"), strtotime($data['ctime2'] . " 23:59:59")]);
            }
        }
//        if ($data['allot_end'] == '0' || $data['allot_end']) {
//            $map['o.allot_end'] = $data['allot_end'];
//        }


        if ($data['collected']||$data['collected']==='0') {
            $map['o.collected'] = $data['collected'];
        }
        if ($data['contacted']||$data['contacted']==='0') {
            $map['o.contacted'] = $data['contacted'];
        }

        if ($data['display_status']) {
            $map['o.display_status'] = $data['display_status'];
        }
        if ($data['dispose_status']) {
            $map['o.dispose_status'] = $data['dispose_status'];
        }

        if ($data['is_review']) {
            $map['o.is_review'] = $data['is_review'];
        }


        $listRows = $this->request->param('numPerPage') ? 20 : Config::get("paginate.list_rows");

        $list = Db::name('order')
            ->alias('o')
            ->join("tp_route r", "r.id=o.route_id", "left")
            ->where($map)
            ->field("o.*,r.title as route_title")
            ->order('o.id', 'desc')
            ->paginate($listRows, false, ['query' => $this->request->get()]);

        $new_list = $list->toArray()['data'];
//        echo Db::name('order')->getLastSql();
        foreach ($new_list as $k => $v) {
            $new_list[$k]['platform'] = Db::name('platform')
                ->where('platform_name', $v['platform'])
                ->value('name');
            $new_list[$k]['order_traveler'] = Db::name('order_traveler')
                ->where('oid', $v['id'])
                ->select();
            $new_list[$k]['remark'] = Db::name('order_remark')
                ->where('order_id', $v['order_id'])
                ->limit('5')
                ->order('id desc')
                ->select();

            // 获取关联订单的关联数据
            if ($v['relevance_id'] != '' || $v['relevance_id'] != null) {
                $new_list[$k]['relevance'] = Db::name('order_relevance')
                    ->alias('or')
                    ->join('tp_order o', 'o.id=or.order_id', 'left')
                    ->join("tp_route r", "r.id=o.route_id", "left")
                    ->field('or.order_id,o.*,r.title as route_title')
                    ->where('relevance', $v['relevance_id'])
                    ->select();
            }
        }

        // 模板赋值显示
        $platform = Db::name('platform')->select();
        $this->view->assign('platform', $platform);
        $this->view->assign('dispose_status', $data['dispose_status']);
        $this->view->assign('display_status', $data['display_status']);
        $this->view->assign('searchCondition', $searchData);
        $this->view->assign('list', $new_list);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        return $this->view->fetch();
    }

    /*
     * 已联系，已收集状态
     */
    public function cont(){
        if(request()->isAjax()){
            $data = input();

            $orderData = model('Order')->find($data['id']);
            if($data['collected']){
                $orderData->collected = $data['select'];
                if($orderData->dispose_status=='no_collection'){
                    $orderData->dispose_status='vehicle_dispatching';
                }
                $result = $orderData->save();
            }
            if($data['contacted']){
                $orderData->contacted = $data['select'];
                if($orderData->dispose_status=='no_contact'){
                    $orderData->dispose_status='no_collection';
                }
                $result = $orderData->save();
            }

            if($result){
                return json(['code' => 1,'msg' => '修改成功','data' => $data]);
            }else{
                return json(['code' => 0,'msg' => '修改失败']);
            }

        }
    }
    /*
     * 已收集状态
     */
//    public function collected(){
//        if(request()->isAjax()){
//            $data = input();
//
//            $orderData = model('Order')->find($data['id']);
//            $orderData->display_status = $data['select'];
//            $result = $orderData->save();
//
//            if($result){
//                return json(['code' => 1,'msg' => '修改成功','data' => $data]);
//            }else{
//                return json(['code' => 0,'msg' => '修改失败']);
//            }
//
//        }
//    }

    /**
     * 导出出行旅客电子表格
     * @return mixed
     */
    public function export_to_excel_traveler(Request $request)
    {
        $data = input();
        ini_set('max_execution_time', 3600);//1小时
        ini_set('memory_limit', '500M');
        Vendor('PHPExcel.PHPExcel');
        Vendor('PHPExcel.PHPExcel.WorkSheet.Drawing');
        Vendor('PHPExcel.PHPExcel.Writer.Excel2007');
        //实例化
        $export_excel = new \PHPExcel();
        //设置文档属性
        $writer = \PHPExcel_IOFactory::createWriter($export_excel, 'Excel2007');
        //设置内容
        $export_sheet = $export_excel->getActiveSheet();
        for ($l = 0; $l < 26; $l++) {
            $letter[] = chr($l + 65);
        }
        $countChr = count($letter);
        for ($j = 0; $j < $countChr; $j++) {
            for ($k = 0; $k < $countChr; $k++) {
                $letter[] = $letter[$j] . $letter[$k];
            }
        }
        $tableHeader = ['id', '姓名', '联系电话', '身份证号码', '地址', '订单号', '人员组ID', '年龄', '性别', '人员组', '住宿情况', '是否在回收站', '车调处理', '房调处理', '备注', '住宿备注', '开始时间', '结束时间', '订单处理状态', '是否异常', '保险金额'];
        $li_length = count($letter);//设置单元格的宽度
        for ($li = 0; $li < $li_length; $li++) {
            $export_sheet->getColumnDimension("$letter[$li]")->setWidth(30);
        }
        $tableLength = count($tableHeader);
        for ($i = 0; $i < $tableLength; $i++) {
            $export_sheet->setCellValue("$letter[$i]1", "$tableHeader[$i]");
        }
        if ($this::$isdelete) {
            $map['o.isdelete'] = 1;
        } else {
            $map['o.isdelete'] = 0;
        }

        //查询要填充表格数据
        $list = Db::name('order_traveler')
            ->where('oid', $data['oid'])
            ->field('status', true)
            ->select();

        foreach ($list as $lk => $lv) {
            $list[$lk]['oid'] = empty($lv['oid']) ? '' : Db::name('order')->where('id', $lv['oid'])->value('order_id');
            $list[$lk]['start_time'] = empty($lv['start_time']) ? '' : date('Y-m-d H:i:s', $lv['start_time']);
            $list[$lk]['end_time'] = empty($lv['end_time']) ? '' : date('Y-m-d H:i:s', $lv['end_time']);
            switch ($lv['isdelete']) {
                case 1:
                    $list[$lk]['isdelete'] = '是';
                    break;
                case 0:
                    $list[$lk]['isdelete'] = '否';
                    break;
            }
            switch ($lv['is_error']) {
                case 1:
                    $list[$lk]['is_error'] = '是';
                    break;
                case 0:
                    $list[$lk]['is_error'] = '否';
                    break;
            }
            switch ($lv['order_processing_status']) {
                case 'no_contact':
                    $list[$lk]['order_processing_status'] = '未联系';
                    break;
                case 'no_collection':
                    $list[$lk]['order_processing_status'] = '未收集';
                    break;
                case 'vehicle_dispatching':
                    $list[$lk]['order_processing_status'] = '可派车';
                    break;
                case 'normal_travel':
                    $list[$lk]['order_processing_status'] = '正常出行';
                    break;
                case 'check':
                    $list[$lk]['order_processing_status'] = '审核';
                    break;
                case 'success_travel':
                    $list[$lk]['order_processing_status'] = '完成出行';
                    break;
                case 'error':
                    $list[$lk]['order_processing_status'] = '异常';
                    break;
            }
        }
        //定义table键
        if (!empty($list)) {
            $tableKey = array_keys($list[0]);
            //填充表格信息
            $tableKeyLength = count($tableKey);
            foreach ($list as $tk => $tv) {
                $tk += 2;
                for ($i = 0; $i < $tableKeyLength; $i++) {
                    $export_sheet->setCellValue("$letter[$i]" . $tk, $tv[$tableKey[$i]]);
                }
            }
        }
        $fileName = date('YmdHis', time()) . "订单ID" . $data['oid'] . "-出行旅客数据.xls";
        $fileName = iconv('utf-8', 'gb2312', $fileName);
        ob_end_clean();

        if ($request->isGet()) {
            header('Content-Type:application/force-download');
            header('Content-Type:application/octet-stream');
            header('Content-Type:application/download');
            header('Content-Disposition:inline;filename=' . $fileName);
            header('Content-Transfer-Encoding:binary');
            header('Cache-Control:must-revalidate,post-check=0');
            header('Pragma:no-cache');
            $writer->save('php://output');
            exit();
        } else {
            // 保存文件到服务器上
            $path = ROOT_PATH . "public/excel";
            // 判断文件是否存在
            if (!file_exists($path)) {
                mkdir($path, 0777, true);
            }
            $fileName = iconv('gb2312', 'utf-8', $fileName);
            $file = $path . "/{$fileName}";
            $writer->save($file);
            $url = $request->domain() . "/excel/{$fileName}";
            return ajax_return_adv($url, '', '', '', '', '', 5);
        }
    }

    /**
     * 导出订单电子表格
     * @return mixed
     */
    public function export_to_excel(Request $request)
    {
        $data = input();
        ini_set('max_execution_time', 3600);//1小时
        ini_set('memory_limit', '500M');
        Vendor('PHPExcel.PHPExcel');
        Vendor('PHPExcel.PHPExcel.WorkSheet.Drawing');
        Vendor('PHPExcel.PHPExcel.Writer.Excel2007');
        //实例化
        $export_excel = new \PHPExcel();
        //设置文档属性
        $writer = \PHPExcel_IOFactory::createWriter($export_excel, 'Excel2007');
        //设置内容
        $export_sheet = $export_excel->getActiveSheet();
        for ($l = 0; $l < 26; $l++) {
            $letter[] = chr($l + 65);
        }
        $countChr = count($letter);
        for ($j = 0; $j < $countChr; $j++) {
            for ($k = 0; $k < $countChr; $k++) {
                $letter[] = $letter[$j] . $letter[$k];
            }
        }
        $tableHeader = ['id', '订单id', '订单状态', '是否退款', '退款状态', '路线id', '金额', '标题', '退款金额', '平台',
            '订单是否启用', '是否放入回收站', '出发时间', '结束时间', '是否分配', '路线', '分配是否完成', '预订人', '邮箱', '电话', '微信', '备注', '所属地区', '是否全额退款', '用车形式', '产品名称', '创建时间',
            '产品id', '发票状态', '点评情况', 'UID', '接机时间', '接机地点', '是否需要接机', '产品名称', '库存名', '订单金额', '已付金额', '商家补贴', '平台补贴', 'OTA产品名称', '处理状态', '是否刷单', '关联ID',
            '是否已安排接送机', '订单标记颜色', '记录更新订单颜色的次数', '订单量', '补缴渠道', '补缴类目', '补缴金额', '支出渠道', '支出类目', '支出金额', '退款渠道', '退款类型', '退款原因'];
        $li_length = count($letter);//设置单元格的宽度
        for ($li = 0; $li < $li_length; $li++) {
            switch ($letter[$li]) {
                case 'A':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(10);
                    break;
                case 'B':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);
                    break;
                case 'C':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(15);
                    break;
                case 'D':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(15);
                    break;
                case 'E':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(15);
                    break;
                case 'F':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(20);
                    break;
                case 'G':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(10);
                    break;
                case 'H':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(50);
                    break;
                case 'I':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(20);
                    break;
                case 'J':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(10);
                    break;
                case 'K':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(15);
                    break;
                case 'S':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(20);
                    break;
                case 'T':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(30);
                    break;
                default:
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(20);
            }
        }
        $tableLength = count($tableHeader);
        for ($i = 0; $i < $tableLength; $i++) {
            $export_sheet->setCellValue("$letter[$i]1", "$tableHeader[$i]");
        }
        if ($this::$isdelete) {
            $map['o.isdelete'] = 1;
        } else {
            $map['o.isdelete'] = 0;
        }
        if ($data['sales_id']) {
            $map['o.sales_id'] = array('like', '%' . $data['sales_id'] . '%');
        }
        if ($data['order_id']) {
            $map['o.order_id'] = array('like', "%{$data['order_id']}%");
        }
        if ($data['booking_people_name']) {
            $map['o.booking_people_name'] = array('like', "%{$data['booking_people_name']}%");
        }
        if ($data['booking_people_phone']) {
            $map['o.booking_people_phone'] = array('like', "%{$data['booking_people_phone']}%");
        }
        if ($data['sku_id']) {
            $map['o.sku_id'] = array('in', $data['sku_id']);
        }

        //选择导出数据
        if ($data['id']) {
            $id = implode($data['id'], ',');
            $map['o.id'] = ['in', $id];
        }

        //表名
        if ($data['search']) {
            switch ($data['search']) {
                case 'all':
                    $tableName = '全部订单';
                    break;
                case 'isallot':
                    $tableName = '已分配订单';
                    $map['o.allot_end'] = true;
                    break;
                case 'refund_order':
                    $tableName = '退款订单数据';
                    $map['o.isrefund'] = true;
                    break;
                default:
                    $tableName = '订单列表';
            }
        }
        //开发票字段
        if ($data['invoice']) {
            $map['o.invoice'] = $data['invoice'];
        }
        if ($data['order_status']) {
            $map['o.order_status'] = $data['order_status'];
        }
        if ($data['isrefund'] == '0' || $data['isrefund']) {
            $map['o.isrefund'] = $data['isrefund'];
        }
        if ($data['platform']) {
            $map['o.platform'] = $data['platform'];
        }
        if ($data['allot_end'] == '0' || $data['allot_end']) {
            $map['o.allot_end'] = $data['allot_end'];
        }
//        if ($data['search'])
        if ($data['date1']) {
            $map['o.start_time'] = array("between", [strtotime($data['date1'] . " 00:00:00"), strtotime($data['date1'] . " 23:59:59")]);

        }
        if ($data['ctime']) {
            $map['o.ctime'] = array("between", [strtotime($data['ctime'] . " 00:00:00"), strtotime($data['ctime'] . " 23:59:59")]);

        }
        //查询要填充表格数据
        $list = Db::name('order')
            ->alias('o')
            ->join("tp_route r", "r.id=o.route_id", "left")
            ->join("tp_mfw_sku sku", "o.sku_id=sku.sku_id", "left")
            ->where($map)
            ->field("o.*")
            ->order('o.id', 'desc')
            ->select();
        foreach ($list as $lk => $lv) {
            $list[$lk]['oid'] = empty($lv['oid']) ? '' : Db::name('order')->where('id', $lv['oid'])->value('order_id');
            $list[$lk]['start_time'] = empty($lv['start_time']) ? '' : date('Y-m-d H:i:s', $lv['start_time']);
            $list[$lk]['end_time'] = empty($lv['end_time']) ? '' : date('Y-m-d H:i:s', $lv['end_time']);
            $list[$lk]['ctime'] = empty($lv['ctime']) ? '' : date('Y-m-d H:i:s', $lv['ctime']);
            //订单状态
            switch ($lv['order_status']) {
                case 'issue':
                    $list[$lk]['order_status'] = '已出单';
                    break;
                case 'pay_for':
                    $list[$lk]['order_status'] = '待付款';
                    break;
                case 'pending':
                    $list[$lk]['order_status'] = '待出单';
                    break;
                case 'finish':
                    $list[$lk]['order_status'] = '已完成';
                    break;
                case 'close':
                    $list[$lk]['order_status'] = '已关闭';
                    break;
            }
            //订单状态
            switch ($lv['status']) {
                case 1:
                    $list[$lk]['status'] = '启用';
                    break;
                case 0:
                    $list[$lk]['status'] = '禁用';
                    break;
            }
            $list[$lk]['money'] = empty($lv['money']) ? '' : $lv['money'] . '￥';
            $list[$lk]['total_price'] = empty($lv['total_price']) ? '' : $lv['total_price'] . '￥';//订单金额
            $list[$lk]['payment_fee'] = empty($lv['payment_fee']) ? '' : $lv['payment_fee'] . '￥';//支付金额
            $list[$lk]['reduce_ota'] = empty($lv['reduce_ota']) ? '' : $lv['reduce_ota'] . '￥';//商家补贴
            $list[$lk]['reduce_mfw'] = empty($lv['reduce_mfw']) ? '' : $lv['reduce_mfw'] . '￥';//平台补贴
            $list[$lk]['refund_money'] = empty($lv['refund_money']) ? '' : $lv['refund_money'] . '￥';//退款金额
            //是否退款
            $list[$lk]['isrefund'] = empty($lv['isrefund']) ? '不退款' : '是退款';
            $list[$lk]['platform'] = empty($lv['platform']) ? '马蜂窝' : '手动添加';
            $list[$lk]['isallot'] = ($lv['isallot'] == 1) ? '已分配' : '未分配';
            $list[$lk]['allot_end'] = ($lv['allot_end'] == 1) ? '是分配完成' : '未分配完成';
            //退款状态
            switch ($lv['refund_status']) {
                case 'check':
                    $list[$lk]['refund_status'] = '审核中';
                    break;
                case 'refunding':
                    $list[$lk]['refund_status'] = '退款中';
                    break;
                case 'refunded':
                    $list[$lk]['refund_status'] = '已退款';
                    break;
                case 'rejected':
                    $list[$lk]['refund_status'] = '拒绝退款';
                    break;
            }
            //路线
            $list[$lk]['route_id'] = empty($lv['route_id']) ? '' : Db::name('route')->where('id', $lv['route_id'])->value('title');
            if ($lv['platform'] == 'mfw') {
                $sku_data = Db::name('mfw_sku')->where('sku_id', $lv['sku_id'])->field('sales_name,sku_name')->find();
                $list[$lk]['sku_id'] = $sku_data['sku_name'];
                $list[$lk]['sales_id'] = $sku_data['sku_name'];
            }
            //发票状态
            switch ($lv['invoice']) {
                case 2:
                    $list[$lk]['invoice'] = '已开发票';
                    break;
                case 3:
                    $list[$lk]['invoice'] = '未开发票';
                    break;
            }
            //平台状态
            $list[$lk]['platform'] = Db::name('platform')->where('platform_name', $lv['platform'])->value('name');
            //点评情况
            switch ($lv['is_review']) {
                case 0:
                    $list[$lk]['is_review'] = '未点评';
                    break;
                case 1:
                    $list[$lk]['is_review'] = '好评';
                    break;
                case 2:
                    $list[$lk]['is_review'] = '差评';
                    break;
            }
            //接机情况
            switch ($lv['is_pick_up']) {
                case 0:
                    $list[$lk]['is_pick_up'] = '不需要';
                    break;
                case 1:
                    $list[$lk]['is_pick_up'] = '需要';
                    break;
            }
            //处理状态
            switch ($lv['dispose_status']) {
                case 'no_contact':
                    $list[$lk]['dispose_status'] = '未联系';
                    break;
                case 'no_collection':
                    $list[$lk]['dispose_status'] = '未收集';
                    break;
                case 'vehicle_dispatching':
                    $list[$lk]['dispose_status'] = '可派车';
                    break;
                case 'normal_travel':
                    $list[$lk]['dispose_status'] = '正常出行';
                    break;
                case 'check':
                    $list[$lk]['dispose_status'] = '审核';
                    break;
                case 'success_travel':
                    $list[$lk]['dispose_status'] = '完成出行';
                    break;
                case 'error':
                    $list[$lk]['dispose_status'] = '异常';
                    break;
            }
        }
        //定义table键
        if (!empty($list)) {
            $tableKey = array_keys($list[0]);
            //填充表格信息
            $tableKeyLength = count($tableKey);
            foreach ($list as $tk => $tv) {
                $tk += 2;
                for ($i = 0; $i < $tableKeyLength; $i++) {
                    $export_sheet->setCellValue("$letter[$i]" . $tk, $tv[$tableKey[$i]]);
                }
            }
        }
        $fileName = date('YmdHis', time()) . "订单管理-{$tableName}数据.xls";
        $fileName = iconv('utf-8', 'gb2312', $fileName);

        ob_end_clean();
        if ($request->isGet()) {
            header('Content-Type:application/force-download');
            header('Content-Type:application/octet-stream');
            header('Content-Type:application/download');
            header('Content-Disposition:inline;filename=' . $fileName);
            header('Content-Transfer-Encoding:binary');
            header('Cache-Control:must-revalidate,post-check=0');
            header('Pragma:no-cache');
            $writer->save('php://output');
            exit();
        } else {
            // 保存文件到服务器上
            $path = ROOT_PATH . "public/excel";
            // 判断文件是否存在
            if (!file_exists($path)) {
                mkdir($path, 0777, true);
            }
            $fileName = iconv('gb2312', 'utf-8', $fileName);
            $file = $path . "/{$fileName}";
            $writer->save($file);
            $url = $request->domain() . "/excel/{$fileName}";
            return ajax_return_adv($url, '', '', '', '', '', 5);
        }
    }

    /**
     * 删除文件
     */

    public function del()
    {
        $data = input();
        if (!$data['val']) {
            return ajax_return_adv_error('缺少参数');
        }
        $fileArr = explode('/', $data['val']);
        $arrLength = count($fileArr);
        $filePath = ROOT_PATH . "public/excel/{$fileArr[$arrLength-1]}";
        if ($data['val'] != 1) {
            if (!file_exists($filePath)) {
                return ajax_return_adv_error('文件不存在');
            }
        }
        // 删除之前存在的文件
        $path = ROOT_PATH . 'public/excel';
        $now_time = time();
        if (file_exists($path)) {
            // 扫描目录
            $fileInfo = scandir($path);
            // 对文件进行截取
            if (!empty($fileInfo)) {
                foreach ($fileInfo as $key => $value) {
                    //	去掉'.'和'..'目录
                    if (mb_strlen($value) < 10) {
                        unset($fileInfo[$key]);
                        continue; // 中止本次循环
                    }
                    $filePath1 = $path . '/' . $value;
                    $fileTime = strtotime(substr($value, 0, 14)) + 600;
                    // 删除10分钟后的过期文件
                    if ($now_time > $fileTime) {
                        if (file_exists($filePath1)) {
                            unlink($filePath1); // 删除文件
                        }
                    }
                }
            }
        }
        if ($filePath&&unlink($filePath)) {
            return ajax_return_adv('删除成功', '', '', '', '', '', 5);
        } else {
            return ajax_return_error('删除失败');
        }
    }


    /**
     * 未分配
     * @return mixed
     */
    public function unallot()
    {

        $data = input();
        if ($data['sales_id']) {
            $map['o.sales_id'] = array('in', $data['sales_id']);
        }
        if ($data['order_id']) {
            $map['o.order_id'] = array('like', "%{$data['order_id']}%");
        }
        if ($data['booking_people_name']) {
            $map['o.booking_people_name'] = array('like', "%{$data['booking_people_name']}%");
        }
        if ($data['booking_people_phone']) {
            $map['o.booking_people_phone'] = array('like', "%{$data['booking_people_phone']}%");
        }
        if ($data['sku_id']) {
            $map['o.sku_id'] = array('in', $data['sku_id']);
        }
        $map['o.order_status'] = array('not in', array('close', 'finish'));
        if ($data['order_status']) {
            $map['o.order_status'] = $data['order_status'];
        }
        if ($data['isrefund'] == '0' || $data['isrefund']) {
            $map['o.isrefund'] = $data['isrefund'];
        }
        if ($data['platform']) {
            $map['o.platform'] = $data['platform'];
        }
        if ($data['allot_end'] == '0' || $data['allot_end']) {
            $map['o.allot_end'] = $data['allot_end'];
        }
        if ($data['ctime']) {
            $map['o.ctime'] = array("between", [strtotime($data['ctime'] . " 00:00:00"), strtotime($data['ctime'] . " 23:59:59")]);

        }
        if ($data['date1']) {
            $map['o.start_time'] = array("between", [strtotime($data['date1'] . " 00:00:00"), strtotime($data['date1'] . " 23:59:59")]);

        }
        if ($data['booking_people_remark']) {
            $map['o.booking_people_remark'] = ['like', '%' . $data['booking_people_remark'] . '%'];
        }
        $map['allot_end'] = false;
        $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");

        $list = Db::name('order')
            ->join("tp_mfw_sku sku", "o.sku_id=sku.sku_id", "left")
            ->alias('o')
            ->where($map)
            ->order('isrefund asc ,id desc')
            ->field('o.*,sku.sku_name')
            ->paginate($listRows, false, ['query' => $this->request->get()]);

        // 模板赋值显示
        $platform = Db::name('platform')->select();
        $this->view->assign('platform', $platform);
        $this->view->assign('list', $list);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        return $this->view->fetch();
    }

    /**
     * 已分配
     * @return mixed
     */
    public function isallot()
    {
        $data = input();
        $url = '/admin/order/isallot_html';
        if ($data) {
            foreach ($data as $dk => $dv) {
                if ($dk == $url) {
                    unset($data[$dk]);
                }
                if (!empty($dv)) {
                    $searchData[$dk] = $dv;
                }
            }
            $searchData['search'] = 'isallot';;
        } else {
            $searchData['search'] = 'isallot';;
        }

        if ($data['sales_id']) {
            $map['o.sales_id'] = array('in', $data['sales_id']);
        }
        if ($data['order_id']) {
            $map['o.order_id'] = array('like', "%{$data['order_id']}%");
        }
        if ($data['booking_people_name']) {
            $map['o.booking_people_name'] = array('like', "%{$data['booking_people_name']}%");
        }
        if ($data['booking_people_phone']) {
            $map['o.booking_people_phone'] = array('like', "%{$data['booking_people_phone']}%");
        }
        if ($data['sku_id']) {
            $map['o.sku_id'] = array('in', $data['sku_id']);
        }

        //是否一开发票
        if ($data['invoice'] == 2) {
            $map['o.invoice'] = 2;//已开发票
        } elseif ($data['invoice'] == 3) {
            $map['o.invoice'] = 3;//未开发票
        }

        if ($data['order_status']) {
            $map['o.order_status'] = $data['order_status'];
        }
        if ($data['isrefund'] == '0' || $data['isrefund']) {
            $map['o.isrefund'] = $data['isrefund'];
        }
        if ($data['platform']) {
            $map['o.platform'] = $data['platform'];
        }

        if ($data['date1']) {
            $map['o.start_time'] = array("between", [strtotime($data['date1'] . " 00:00:00"), strtotime($data['date1'] . " 23:59:59")]);

        }
        $map['o.allot_end'] = true;
        $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");

        $list = Db::name('order')
            ->join("tp_mfw_sku sku", "o.sku_id=sku.sku_id", "left")
            ->alias('o')
            ->where($map)
            ->order('id', 'desc')
            ->field('o.*,sku.sku_name')
            ->paginate($listRows, false, ['query' => $this->request->get()]);

        // 模板赋值显示
        $platform = Db::name('platform')->select();
        $this->view->assign('Request.param.ctime', $data);
        $this->view->assign('$Request.param.start_time', $data);
        $this->view->assign('platform', $platform);
        $this->view->assign('list', $list);
        $this->view->assign('searchCondition', $searchData);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        return $this->view->fetch();
    }

    /**
     * 退款订单
     * @return mixed
     */
    public function refund_order()
    {
        $data = input();
        $url = '/admin/order/refund_order_html';
        if ($data) {
            foreach ($data as $dk => $dv) {
                if ($dk == $url) {
                    unset($data[$dk]);
                }
                if (!empty($dv)) {
                    $searchData[$dk] = $dv;
                }
            }
            $searchData['search'] = 'refund_order';;
        } else {
            $searchData['search'] = 'refund_order';;
        }
        if ($data['sales_id']) {
            $map['o.sales_id'] = array('in', $data['sales_id']);
        }
        if ($data['order_id']) {
            $map['o.order_id'] = array('like', "%{$data['order_id']}%");
        }
        if ($data['booking_people_name']) {
            $map['o.booking_people_name'] = array('like', "%{$data['booking_people_name']}%");
        }
        if ($data['booking_people_phone']) {
            $map['o.booking_people_phone'] = array('like', "%{$data['booking_people_phone']}%");
        }
        if ($data['sku_id']) {
            $map['o.sku_id'] = array('in', $data['sku_id']);
        }

        if ($data['order_status']) {
            $map['o.order_status'] = $data['order_status'];
        }
        if ($data['isrefund'] == '0' || $data['isrefund']) {
            $map['o.isrefund'] = $data['isrefund'];
        }
        if ($data['platform']) {
            $map['o.platform'] = $data['platform'];
        }
        if ($data['allot_end'] == '0' || $data['allot_end']) {
            $map['o.allot_end'] = $data['allot_end'];
        }
        if ($data['date1']) {
            $map['o.start_time'] = array("between", [strtotime($data['date1'] . " 00:00:00"), strtotime($data['date1'] . " 23:59:59")]);

        }
        if ($data['ctime']) {
            $map['o.ctime'] = array("between", [strtotime($data['ctime'] . " 00:00:00"), strtotime($data['ctime'] . " 23:59:59")]);

        }
        $map['isrefund'] = true;
        $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");

        $list = Db::name('order')
            ->alias('o')
            ->join("tp_mfw_sku sku", "o.sku_id=sku.sku_id", "left")
            ->where($map)
            ->order('id', 'desc')
            ->field('o.*,sku.sku_name')
            ->paginate($listRows, false, ['query' => $this->request->get()]);

        // 模板赋值显示
        $platform = Db::name('platform')->select();
        $this->view->assign('platform', $platform);
        $this->view->assign('list', $list);
        $this->view->assign('searchCondition', $searchData);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        return $this->view->fetch();
    }

    /**
     * 添加
     * @return mixed
     */
    public function add()
    {
        $data = input();
        $time = date('Y-m-d', time());
        logs("{$time}添加订单", $data);
        if ($this->request->isAjax()) {
            if (!$data['order_id']) {
                $data['order_id'] = get_order_id();
            }
            if($data['dispose_status']=='no_contact'){
                $data['contacted']=false;
            }
            if($data['no_collection']=='no_collection'){
                $data['collected']=false;
            }
            // 验证数据
            $rule = [
                'start_time' => 'require',
                'end_time' => 'require',
                'platform' => 'require',
                'title' => 'require',
            ];
            $message = [
                'start_time.require' => '开始时间不能为空',
                'end_time.require' => '结束时间不能为空',
                'platform.require' => '平台不能为空',
                'title.require' => '标题不能为空',
            ];
            $validate = new Validate($rule, $message);
            $result = $validate->check($data);
            if (!$result) {
                return ajax_return_adv_error($validate->getError());
            }
//            dump($data);
            if (!empty($data['start_time']) && !empty($data['end_time']) && ($data['start_time'] > $data['end_time'])) {
                return ajax_return_adv_error('订单的开始日期不能大于结束日期');
            }

            $data['sales_name'] = $data['title'];
            $data['start_time'] = strtotime($data['start_time']);
            $data['end_time'] = strtotime($data['end_time']);
            $data['ctime'] = strtotime($data['ctime']);
            $data['pick_up_time'] = $data['pick_up_time'];
            $oid = Db::name('order')->insertGetId($data);
            $travelers = [];

            if (is_array($data['traveler']['name'])) {
                foreach ($data['traveler']['name'] as $key => $vle) {
                    if (empty($data['traveler']['name'][$key])) {
                        return ajax_return_adv_error('旅客名字不能为空');
                    }
                    $traveler['name'] = $data['traveler']['name'][$key];
                    $traveler['phone'] = $data['traveler']['phone'][$key];
                    $traveler['id_card'] = $data['traveler']['id_card'][$key];
                    $traveler['address'] = $data['traveler']['address'][$key];
                    $traveler['age'] = $data['traveler']['age'][$key];
                    $traveler['sex'] = $data['traveler']['sex'][$key];
                    $traveler['group'] = $data['traveler']['group'][$key];
                    $traveler['hotel'] = $data['traveler']['hotel'][$key];
                    $traveler['remark'] = $data['traveler']['remark'][$key];
                    $traveler['accommodation'] = $data['traveler']['accommodation'][$key];
                    if($data['traveler']['insurance_money'][$key]){
                        $traveler['insurance_money'] = $data['traveler']['insurance_money'][$key];
                    }
                    if($data['traveler']['isaccommodation'][$key]){
                        $traveler['isaccommodation'] = $data['traveler']['isaccommodation'][$key];
                    }
                    $traveler['oid'] = $oid;
                    $travelers[] = $traveler;
                }
            }

            if ($oid) {
                if ($travelers) {
                    $re = Db::name('order_traveler')->insertAll($travelers);
                    if ($re) {
                        // 将包含住宿的订单数组统计到控房表
                        $ret = self::addAccommodation($oid);
                        logs('addAccommodation', $ret);
                        return ajax_return_adv("添加成功");
                    }
                } else {
                    return ajax_return_adv("添加成功");
                }

            }
            return ajax_return_error("添加失败");
        } else {
            //获取平台列表
            $platform = Db::name('platform')->select();
            //获取等级列表
            $route_list = Db::name('route')->where('isdelete', 0)->select();
            $this->view->assign('route_list', $route_list);
            $this->view->assign('platform_list', $platform);
            return $this->view->fetch("edit");
        }
    }

    /**
     * 编辑
     * @return mixed
     */
    public function edit()
    {
        $data = input();

        if (!isset($data['id'])) {
            throw new \think\Exception('缺少id参数');
        }
        if ($this->request->isAjax()) {
            if (!$data['order_id']) {
                $data['order_id'] = get_order_id();
            }

            if($data['dispose_status']=='no_contact'){
                $data['contacted']=false;
            }
            if($data['no_collection']=='no_collection'){
                $data['collected']=false;
            }
            // 验证数据
            $rule = [
                'title' => 'require',
                'start_time' => 'require',
                'end_time' => 'require',
                'platform' => 'require',
            ];
            $message = [
                'start_time.require' => '开始时间不能为空',
                'end_time.require' => '结束时间不能为空',
                'platform.require' => '平台不能为空',
                'title.require' => '标题不能为空',
            ];
            $validate = new Validate($rule, $message);
            $result = $validate->check($data);
            if (!$result) {
                return ajax_return_adv_error($validate->getError());
            }
            $oid = $data['id'];
            $old_order = Db::name('order')->where('id', $oid)->find();
            if ($old_order['isallot'] || $old_order['order_status'] == "close" || $old_order['order_status'] == "finish") {
                return ajax_return_error("订单已分配或已结束");
            }

            $travelers = [];
            $data['sales_name'] = $data['title'];
            $data['start_time'] = strtotime($data['start_time']);
            $data['end_time'] = strtotime($data['end_time']);
            $data['pick_up_time'] = $data['pick_up_time'];
            $data['ctime'] = strtotime($data['ctime']);

            if (is_array($data['traveler']['name'])) {
                foreach ($data['traveler']['name'] as $key => $vle) {
                    if (empty($data['traveler']['name'][$key])) {
                        return ajax_return_adv_error('旅客名字不能为空');
                    }
                    $traveler['id'] = $data['traveler']['id'][$key];
                    $traveler['name'] = $data['traveler']['name'][$key];
                    $traveler['phone'] = $data['traveler']['phone'][$key];
                    $traveler['id_card'] = $data['traveler']['id_card'][$key];
                    $traveler['age'] = $data['traveler']['age'][$key];
                    $traveler['sex'] = $data['traveler']['sex'][$key];
                    $traveler['group'] = $data['traveler']['group'][$key];
                    $traveler['hotel'] = $data['traveler']['hotel'][$key];
                    $traveler['address'] = $data['traveler']['address'][$key];
                    $traveler['remark'] = $data['traveler']['remark'][$key];
                    $traveler['accommodation'] = $data['traveler']['accommodation'][$key];
                    $traveler['insurance_money'] = $data['traveler']['insurance_money'][$key];
                    $traveler['isaccommodation'] = $data['traveler']['isaccommodation'][$key];
                    $traveler['oid'] = $oid;
                    $travelers[] = $traveler;


                }
            }
            $new_order = $data;
            $new_order['travelers'] = $travelers;
            $new_order['order_id'] = $data['id'];
            $old_travelers = Db::name("order_traveler")->where('oid', $oid)->select();
            $old_order['travelers'] = $old_travelers;

            $OrderCheck = model("OrderCheck")->check($new_order, $old_order);
            $OrderCheck->add_order_check();
            $OrderCheck->add_exceptional_order();
            Db::name('order')->where('id', $data['id'])->update($data);
            //添加部分
            $add_travelers = [];
            foreach ($travelers as $value) {
                if (!$value['id']) {
                    $add_traveler = $value;
                    $add_travelers[] = $add_traveler;

                }
            }
            if ($add_travelers) {

                Db::name('order_traveler')->insertAll($add_travelers);
            }
            //更改部分
            $update_travelers = [];
            foreach ($travelers as $value) {
                if ($value['id']) {
                    $update_traveler = $value;
                    $update_travelers[] = $update_traveler;
                }
            }
            foreach ($update_travelers as $update_traveler) {
                $_traveler_id = $update_traveler['id'];
                unset($update_traveler['id']);
                Db::name('order_traveler')->where('id', $_traveler_id)->update($update_traveler);
            }

            //删除部分
            $update_traveler_ids = [];
            foreach ($travelers as $value) {
                if ($value['id']) {
                    $update_traveler_ids[] = $value['id'];
                }
            }
            $delete_traveler_ids = [];
            foreach ($old_travelers as $value) {
                if (!in_array($value['id'], $update_traveler_ids)) {
                    $delete_traveler_ids[] = $value['id'];
                }
            }
            if (!empty($data['start_time']) && !empty($data['end_time']) && ($data['start_time'] > $data['end_time'])) {
                return ajax_return_adv_error('订单的开始日期不能大于结束日期');
            }
            $del_map['id'] = array('in', $delete_traveler_ids);
            Db::name('order_traveler')->where($del_map)->delete();


            return ajax_return_adv("修改成功");
        } else {

            $vo = Db::name('order')->where('id', $data['id'])->find();
//            halt($vo);
            $this->view->assign('vo', $vo);
            $list = Db::name('order_traveler')->where('oid', $data['id'])->select();

            //获取平台列表
            $platform = Db::name('platform')->select();
//            halt($platform);
            $this->view->assign('travelers', $list);
            //获取等级列表
            $route_list = Db::name('route')->select();
            $this->view->assign('route_list', $route_list);
            $this->view->assign('platform_list', $platform);
            return $this->view->fetch();
        }
    }

    /**
     * 处理异常
     * @return mixed
     */
    public function dispose_error()
    {
        $data = input();

        if (!isset($data['id'])) {
            throw new \think\Exception('缺少id参数');
        }
        if ($this->request->isAjax()) {
            if (!$data['order_id']) {
                $data['order_id'] = get_order_id();
            }

            // 验证数据
            $rule = [
                'title' => 'require',
                'start_time' => 'require',
                'end_time' => 'require',
                'platform' => 'require',
            ];
            $message = [
                'start_time.require' => '开始时间不能为空',
                'end_time.require' => '结束时间不能为空',
                'platform.require' => '平台不能为空',
                'title.require' => '标题不能为空',
            ];
            $validate = new Validate($rule, $message);
            $result = $validate->check($data);
            if (!$result) {
                return ajax_return_adv_error($validate->getError());
            }

            if ($data['isrefund'] && $data['isrefund'] == 1) {
                $rule_reefund = [
                    'refund_type' => 'require|in:1,2,3,4',
                    'refund_reason' => 'require',
                ];
                $message_reefund = [
                    'refund_type.require' => '退款类型不能为空',
                    'refund_type.in' => '请选择正确的退款类型',
                    'refund_reason.require' => '退款原因不能为空',
                ];
                if ($data['refund_status'] && !empty($data['refund_status'])) {//退款状态不为空时
                    $rule_reefund['refund_status'] = 'in:check,refunding,refunded,rejected';
                    $message_reefund['refund_status.in'] = '请选择正确的退款状态';
                }
                if ($data['refund_type'] == 4) {//退款类型为不退款
                    unset($data['refund_money']);
                    unset($data['refund_channels']);
                } else {
                    $rule_reefund['refund_money'] = 'require|number';
                    $rule_reefund['refund_channels'] = 'require';
                    $message_reefund['refund_money.require'] = '退款金额不能为空';
                    $message_reefund['refund_money.number'] = '退款金额格式错误';
                    $message_reefund['refund_channels.require'] = '退款渠道不能为空';
                }
                $validate_reefund = new Validate($rule_reefund, $message_reefund);
                $result_reefund = $validate_reefund->check($data);
                if (!$result_reefund) {
                    return ajax_return_adv_error($validate_reefund->getError());
                }
                $refund_traveler = '';
                $refund_data = [
                    'oid' => $data['id'],
                    'refund_status' => $data['refund_status'],
                    'refund_money' => $data['refund_money'],
                    'refund_channels' => $data['refund_channels'],
                    'refund_type' => $data['refund_type'],
                    'refund_reason' => $data['refund_reason'],
                ];

//                return ajax_return_adv_error('123');
                $ck = Db::name('order_refund')->where('oid', $data['id'])->find();
                if ($ck) {
                    $refund_data['update_time'] = time();
                    //更新该退款记录
                    Db::name('order_refund')->strict(false)->where('oid', $data['id'])->update($refund_data);
                } else {
                    $refund_data['create_time'] = time();
                    $refund_data['update_time'] = time();
                    //插入退款记录
                    Db::name('order_refund')->strict(false)->insert($refund_data);
                }
            } else {
                //查询是否存在该退款记录
                $ck = Db::name('order_refund')->where('oid', $data['id'])->find();
                if ($ck) {
                    //删除该退款记录
                    Db::name('order_refund')->where('oid', $data['id'])->delete();
                }
                if ($data['refund_status']) {
                    unset($data['refund_status']);
                }
                if ($data['refund_type']) {
                    unset($data['refund_type']);
                }
                if ($data['refund_channels']) {
                    unset($data['refund_channels']);
                }
                if ($data['refund_money']) {
                    unset($data['refund_money']);
                }
                if ($data['refund_reason']) {
                    unset($data['refund_reason']);
                }
            }
            $oid = $data['id'];
            $old_order = Db::name('order')->where('id', $oid)->find();
//            if ($old_order['isallot'] || $old_order['order_status'] == "close" || $old_order['order_status'] == "finish") {
//                return ajax_return_error("订单已分配或已结束");
//            }

            $travelers = [];
            $data['start_time'] = strtotime($data['start_time']);
            $data['end_time'] = strtotime($data['end_time']);
            $data['pick_up_time'] = strtotime($data['pick_up_time']);
            $data['ctime'] = strtotime($data['ctime']);

            if (is_array($data['traveler']['name'])) {
                foreach ($data['traveler']['name'] as $key => $vle) {
                    if (empty($data['traveler']['name'][$key])) {
                        return ajax_return_adv_error('旅客名字不能为空');
                    }
                    $traveler['id'] = $data['traveler']['id'][$key];
                    $traveler['name'] = $data['traveler']['name'][$key];
                    $traveler['phone'] = $data['traveler']['phone'][$key];
                    $traveler['id_card'] = $data['traveler']['id_card'][$key];
                    $traveler['age'] = $data['traveler']['age'][$key];
                    $traveler['sex'] = $data['traveler']['sex'][$key];
                    $traveler['group'] = $data['traveler']['group'][$key];
                    $traveler['hotel'] = $data['traveler']['hotel'][$key];
                    $traveler['address'] = $data['traveler']['address'][$key];
                    $traveler['remark'] = $data['traveler']['remark'][$key];
                    $traveler['accommodation'] = $data['traveler']['accommodation'][$key];
                    $traveler['isaccommodation'] = $data['traveler']['isaccommodation'][$key];
                    $traveler['oid'] = $oid;
                    $travelers[] = $traveler;


                }
            }
            $new_order = $data;
            $new_order['travelers'] = $travelers;
            $new_order['order_id'] = $data['id'];


            $old_travelers = Db::name("order_traveler")->where('oid', $oid)->select();
            $old_order['travelers'] = $old_travelers;

            $OrderCheck = model("OrderCheck")->check($new_order, $old_order);
            $OrderCheck->add_order_check();
            $OrderCheck->add_exceptional_order();
            Db::name('order')->where('id', $data['id'])->update($data);
            //添加部分
            $add_travelers = [];
            foreach ($travelers as $value) {
                if (!$value['id']) {
                    unset($value['id']);
                    $add_traveler = $value;
                    $add_travelers[] = $add_traveler;

                }
            }
            if ($add_travelers) {

                Db::name('order_traveler')->insertAll($add_travelers);
            }
            //更改部分
            $update_travelers = [];
            foreach ($travelers as $value) {
                if ($value['id']) {
                    $update_traveler = $value;
                    $update_travelers[] = $update_traveler;
                }
            }
            foreach ($update_travelers as $update_traveler) {
                $_traveler_id = $update_traveler['id'];
                unset($update_traveler['id']);
                Db::name('order_traveler')->where('id', $_traveler_id)->update($update_traveler);
            }

            //删除部分
            $update_traveler_ids = [];
            foreach ($travelers as $value) {
                if ($value['id']) {
                    $update_traveler_ids[] = $value['id'];
                }
            }
            $delete_traveler_ids = [];
            foreach ($old_travelers as $value) {
                if (!in_array($value['id'], $update_traveler_ids)) {
                    $delete_traveler_ids[] = $value['id'];
                }
            }
            if (!empty($data['start_time']) && !empty($data['end_time']) && ($data['start_time'] > $data['end_time'])) {
                return ajax_return_adv_error('订单的开始日期不能大于结束日期');
            }
            $del_map['id'] = array('in', $delete_traveler_ids);
            Db::name('order_traveler')->where($del_map)->delete();

            // 订单下旅客设置为没有异常
            Db::name('order_traveler')
                ->alias('ot')
                ->join('order o', 'o.id=ot.oid', 'left')
                ->where('o.id', $data['id'])
                ->field('ot.*')
                ->setField('ot.is_error', 0);

            return ajax_return_adv("修改成功");
        } else {

            $vo = Db::name('order')->where('id', $data['id'])->find();
            $this->view->assign('vo', $vo);
            $list = Db::name('order_traveler')->where('oid', $data['id'])->select();

            //获取平台列表
            $platform = Db::name('platform')->select();
            $this->view->assign('travelers', $list);
            //获取等级列表
            $route_list = Db::name('route')->select();
            $this->view->assign('route_list', $route_list);
            $this->view->assign('platform', $platform);
            return $this->view->fetch();
        }
    }

    /*
   * 取消行程
   * @return mixed
   */
    public function close_order()
    {
        $data = input();

        $result = Db::name('order')
            ->where('order_id', $data['order_id'])
            ->setField('order_status', 'close');

        if (!$result) {
            return ajax_return_error("取消失败");
        } else {
            return ajax_return_adv('取消成功');
        }
    }

    /*
     * 设置异常订单
     * @return mixed
     */
    public function error_order()
    {
        $data = input();

        $result = Db::name('order')
            ->where('order_id', $data['order_id'])
            ->setField('dispose_status', 'error');

        // 订单下旅客设置为异常
        Db::name('order_traveler')
            ->alias('ot')
            ->join('order o', 'o.id=ot.oid', 'left')
            ->where('o.order_id', $data['order_id'])
            ->field('ot.*')
            ->setField('ot.is_error', 1);


        if (!$result) {
            return ajax_return_error("设置失败");
        } else {
            return ajax_return_adv('设置成功');
        }
    }

    /**
     * 退款
     * @return mixed
     */
    public function refund()
    {
        $data = input();

        $result = Db::name('order')
            ->where('id', $data['id'])
            ->update([
                'isrefund' => 1,
                'refund_status' => 'refunded'
            ]);

        if (!$result) {
            return ajax_return_error("退款失败");
        }
    }

    /**
     * 异常订单
     * @return mixed
     */
    public function exceptional()
    {
        $exceptional_orders = Db::name('exceptional_order')->where('oid', input('oid'))->select();
        $this->view->assign('list', $exceptional_orders);
        return $this->view->fetch();
    }

    /**
     * 保存出行人员
     * @return mixed
     */
    public function save_traveler()
    {
        $data = input();

        $oid = $data['id'];
        $old_order = Db::name('order')->where('id', $oid)->find();

        if ($old_order['isallot'] || $old_order['order_status'] == "close" || $old_order['order_status'] == "finish") {
            return ajax_return_error("订单已分配或已结束");
        }

        $travelers = [];

        if (is_array($data['traveler']['name'])) {
            foreach ($data['traveler']['name'] as $key => $vle) {
                if (empty($data['traveler']['name'][$key])) {
                    return ajax_return_adv_error('旅客名字不能为空');
                }
                $traveler['id'] = $data['traveler']['id'][$key];
                $traveler['name'] = $data['traveler']['name'][$key];
                $traveler['phone'] = $data['traveler']['phone'][$key];
                $traveler['id_card'] = $data['traveler']['id_card'][$key];
                $traveler['age'] = $data['traveler']['age'][$key];
                $traveler['sex'] = $data['traveler']['sex'][$key];
                $traveler['group'] = $data['traveler']['group'][$key];
                $traveler['hotel'] = $data['traveler']['hotel'][$key];
                $traveler['address'] = $data['traveler']['address'][$key];
                $traveler['remark'] = $data['traveler']['remark'][$key];
                $traveler['accommodation'] = $data['traveler']['accommodation'][$key];
                $traveler['insurance_money'] = $data['traveler']['insurance_money'][$key];
                $traveler['isaccommodation'] = $data['traveler']['isaccommodation'][$key];
                $traveler['oid'] = $oid;
                $travelers[] = $traveler;
            }
        }
        $new_order = $data;
        $new_order['travelers'] = $travelers;
        $new_order['order_id'] = $data['id'];

        $old_travelers = Db::name("order_traveler")->where('oid', $oid)->select();
        $old_order['travelers'] = $old_travelers;

        $OrderCheck = model("OrderCheck")->check($new_order, $old_order);
        $OrderCheck->add_order_check();
        $OrderCheck->add_exceptional_order();
        Db::name('order')->where('id', $data['id'])->update($data);
        //添加部分
        $add_travelers = [];
        foreach ($travelers as $value) {
            if (!$value['id']) {
                unset($value['id']);
                $add_traveler = $value;
                $add_travelers[] = $add_traveler;
            }
        }
        if ($add_travelers) {
            Db::name('order_traveler')->insertAll($add_travelers);
        }
        //更改部分
        $update_travelers = [];
        foreach ($travelers as $value) {
            if ($value['id']) {
                $update_traveler = $value;
                $update_travelers[] = $update_traveler;
            }
        }
        foreach ($update_travelers as $update_traveler) {
            $_traveler_id = $update_traveler['id'];
            unset($update_traveler['id']);
            Db::name('order_traveler')->where('id', $_traveler_id)->update($update_traveler);
        }

        //删除部分
        $update_traveler_ids = [];
        foreach ($travelers as $value) {
            if ($value['id']) {
                $update_traveler_ids[] = $value['id'];
            }
        }
        $delete_traveler_ids = [];
        foreach ($old_travelers as $value) {
            if (!in_array($value['id'], $update_traveler_ids)) {
                $delete_traveler_ids[] = $value['id'];
            }
        }
        $del_map['id'] = array('in', $delete_traveler_ids);
        Db::name('order_traveler')->where($del_map)->delete();

        if ($old_order['dispose_status'] === 'no_contact' || $old_order['dispose_status'] === 'no_collection') {
            Db::name('order')
                ->where('id', $oid)
                ->setField('dispose_status', 'vehicle_dispatching');
        }

        return ajax_return_adv("修改成功");
    }

    /**
     * 修改标记颜色
     * @return mixed
     */
    public function select_color()
    {
        $data = input();

        $result = Db::name('order')
            ->where('order_id', $data['order_id'])
            ->setField('color', $data['color']);

        if ($result) {
            return ajax_return_adv("修改成功");
        } else {
            return ajax_return_adv_error('修改失败');
        }
    }

    /**
     * 修改用车形式
     * @return mixed
     */
    public function select_car_type()
    {
        $data = input();

        $result = Db::name('order')
            ->where('order_id', $data['order_id'])
            ->setField('car_form', $data['car_form']);

        if ($result) {
            return ajax_return_adv("修改成功");
        } else {
            return ajax_return_adv_error('修改失败');
        }
    }

    /**
     * 修改产品类型
     * @return mixed
     */
    public function product_car_type()
    {
        $data = input();

        $result = Db::name('order')
            ->where('order_id', $data['order_id'])
            ->setField('product_type', $data['product_type']);

        if ($result) {
            return ajax_return_adv("修改成功");
        } else {
            return ajax_return_adv_error('修改失败');
        }
    }

    /**
     * 修改接机信息和状态
     * @return mixed
     */
    public function edit_pick()
    {
        $data = input();

        if ($this->request->isAjax()) {
            $result = Db::name('order')
                ->where('id', $data['id'])
                ->update([
                    'is_pick_up' => 1,
                    'pick_up_location' => $data['pick_up_location'],
                    'pick_up_time' => $data['pick_up_time']
                ]);

            if ($result) {
                return ajax_return_adv('编辑成功');
            } else {
                return ajax_return_adv_error('编辑失败');
            }
        } else {

            $result = Db::name('order')
                ->where('id', $data['id'])
                ->field('pick_up_location,pick_up_time')
                ->find();
            $this->view->assign('vo', $result);
            return $this->view->fetch();
        }
    }

    /**
     * 修改接机状态
     * @return mixed
     */
//    public function edit_pick_up()
//    {
//        $data = input();
//
//        $flag = Db::name('order')
//            ->where('order_id', $data['order_id'])
//            ->value('is_pick_up');
//
//        $result = Db::name('order')
//            ->where('order_id', $data['order_id'])
//            ->setField('is_pick_up', !$flag);
//
//        if ($result) {
//            return ajax_return_adv("修改成功");
//        } else {
//            return ajax_return_adv_error('修改失败');
//        }
//    }

    /**
     * 查看备注列表
     * @return mixed
     */
    public function remark()
    {
        $data = input();

        $result = Db::name('order_remark')
            ->where('order_id', $data['order_id'])
            ->order('id desc')
            ->select();

        $this->view->assign('list', $result);
        return $this->view->fetch();
    }

    /**
     * 添加备注
     * @return mixed
     */
    public function add_remark()
    {
        $data = input();

        $realname = Db::name('admin_user_info')
            ->where('id', UID)
            ->value('realname');

        if (UID === 1) {
            $role = '超级管理员';
        } else {
            $role = Db::name('admin_role_user')
                ->alias('aru')
                ->join('tp_admin_role ar', 'ar.id=aru.role_id', 'left')
                ->where('aru.user_id', UID)
                ->value('ar.name');
        }

        $result = Db::name('order_remark')
            ->insert([
                'order_id' => $data['order_id'],
                'realname' => $realname,
                'role' => $role,
                'content' => $data['remark'],
                'create_time' => time()
            ]);

        if ($result) {
            return ajax_return_adv("添加成功");
        } else {
            return ajax_return_adv_error('添加失败');
        }
    }

    /**
     * 手动同步
     * @return mixed
     */
    public function sync_order()
    {
        $api = new \app\common\model\MfwApi();
        $data['order_id']=input('order_id');
        $api->save_syn_order($data);
//        \app\common\model\OrderCheck::task(input('order_id'));
        return ajax_return_adv('已同步');
    }

    /**
     * 取消关联订单
     * @return mixed
     */
    public function close_relevance_order()
    {
        $data = input();

        $relevance_id = Db::name('order')
            ->where('id', $data['id'])
            ->value('relevance_id');

        Db::name('order')
            ->where('id', $data['id'])
            ->setField('relevance_id', null);

        Db::name('order_relevance')
            ->where('relevance', $relevance_id)
            ->where('order_id', $data['id'])
            ->delete();

        return ajax_return_adv('取消关联成功');
    }

    /**
     * 关联订单
     * @return mixed
     */
    public function relevance_order()
    {

        $data = input();

        if ($data['id'] === "") {
            return ajax_return_adv_error('请选择需要关联的订单!');
        }

        $data['id'] = explode(',', $data['id']);

        $route_id = [];
        foreach ($data['id'] as $k => $v) {
            $route_id[$k] = Db::name('order')
                ->where('id', $v)
                ->value('route_id');

            if ($route_id[$k] === null) {
                return ajax_return_adv_error('订单路线为空,请先设置订单路线!');
            }
        }

        $route_id = array_unique($route_id);

        $flag = count($route_id);

        if ($flag != 1) {
            return ajax_return_adv_error('订单路线不一致,关联订单失败!');
        }

        // 移除旧的关联关系
        foreach ($data['id'] as $k => $v) {
            $relevance_id = Db::name('order')
                ->where('id', $v)
                ->value('relevance_id');

            Db::name('order_relevance')
                ->where('relevance', $relevance_id)
                ->where('order_id', $v)
                ->delete();
        }

        $relevance = Db::name('order_relevance')
            ->insertGetId([
                'relevance' => 0,
                'order_id' => 0
            ]);

        $inserts = [];
        foreach ($data['id'] as $k => $v) {
            $insert['relevance'] = $relevance;
            $insert['order_id'] = $v;
            $inserts[] = $insert;
        };

        Db::name('order_relevance')
            ->insertAll($inserts);

        Db::name('order')
            ->whereIn('id', $data['id'])
            ->setField('relevance_id', $relevance);

        return ajax_return_adv('关联成功');
    }

    /**
     * 批量发送短信(缺少发票)
     * @return mixed
     */
    public function batch_send_hint()
    {
        $data = input();

        if (!isset($data['id'])) {
            return ajax_return_adv_error('没有选择派车单，请重试');
        }

        $success = 0;
        $error = 0;
        $error_id = [];
        foreach ($data['id'] as $k => $v) {

            $order = Db::name('dispatch_traveler_group')
                ->alias('dtg')
                ->join('tp_admin_user au', 'dtg.driver_user_id=au.id', 'left')
                ->where('dtg.id', $v)
                ->field('dtg.*,au.mobile')
                ->find();

            $mobile = $order['mobile'];
            if (!$order['mobile'] || !$order['id']) {
                $error = $error + 1;
                $error_id[] = $v;
            }
            $argv = array(
                'name' => '18694047848',     //必填参数。用户账号
                'pwd' => '9FA6EB4D075A98F84F896CF0D451',     //必填参数。（web平台：基本资料中的接口密码）
                'content' => '温馨提示：因您提交的发票金额已小于公司结算的金额，影响本次运费结算，请您尽快提交发票至公司财务，在补齐发票的情况下，公司于3天内结算运费，谢谢配合.',   //必填参数。发送内容（1-500 个汉字）UTF-8编码
                'mobile' => $mobile,   //必填参数。手机号码。多个以英文逗号隔开
                'stime' => '',   //可选参数。发送时间，填写时已填写的时间发送，不填时为当前时间发送
                'sign' => '青海精灵国旅',    //必填参数。用户签名。
                'type' => 'pt',  //必填参数。固定值 pt
                'extno' => ''    //可选参数，扩展码，用户定义扩展码，只能为数字
            );

            //构造要post的字符串
            $flag = 0;
            $params = '';//要post的数据
            foreach ($argv as $key => $value) {
                if ($flag != 0) {
                    $params .= "&";
                    $flag = 1;
                }
                $params .= $key . "=";
                $params .= urlencode($value);// urlencode($value);
                $flag = 1;
            }
            $url = "http://web.wasun.cn/asmx/smsservice.aspx?" . $params; //提交的url地址

            $con = substr(file_get_contents($url), 0, 1);  //获取信息发送后的状态

            if ($con == '0') {
                $success = $success + 1;
            } else {
                $error = $error + 1;
                $error_id[] = $v;
            }
        }
        if (count($error_id) === 0) {
            $msg = '成功发送：' . $success . '条。失败发送' . $error . "条。";
        } else {
            $temp = implode(',', $error_id);
            $msg = '成功发送：' . $success . '条。失败发送' . $error . "条。失败的派车单ID为：" . $temp . "。";
        }
        return ajax_return_adv($msg);
    }

    /**
     * 批量发送短信
     * @return mixed
     */
    public function batch_send()
    {
        $data = input();
        if (!isset($data['id'])) {
            return ajax_return_adv_error('没有选择订单，请重试');
        }

        $success = 0;
        $error = 0;
        $error_id = [];
        foreach ($data['id'] as $k => $v) {
            $order = Db::name("order")->where('id', $v)->find();
            $url = get_host() . "/traveller/order_traveller/index?id={$order['order_id']}";
            $mobile = $order['booking_people_phone'];
            if (!$order['booking_people_phone'] || !$order['order_id']) {
                $error = $error + 1;
                $error_id[] = $v;
            }
            $argv = array(
                'name' => '18694047848',     //必填参数。用户账号
                'pwd' => '9FA6EB4D075A98F84F896CF0D451',     //必填参数。（web平台：基本资料中的接口密码）
                'content' => '请填写你的旅客信息：' . $url . '，请勿将链接提供给他人。',   //必填参数。发送内容（1-500 个汉字）UTF-8编码
                'mobile' => $mobile,   //必填参数。手机号码。多个以英文逗号隔开
                'stime' => '',   //可选参数。发送时间，填写时已填写的时间发送，不填时为当前时间发送
                'sign' => '青海精灵国旅',    //必填参数。用户签名。
                'type' => 'pt',  //必填参数。固定值 pt
                'extno' => ''    //可选参数，扩展码，用户定义扩展码，只能为数字
            );

            //构造要post的字符串
            $flag = 0;
            $params = '';//要post的数据
            foreach ($argv as $key => $value) {
                if ($flag != 0) {
                    $params .= "&";
                    $flag = 1;
                }
                $params .= $key . "=";
                $params .= urlencode($value);// urlencode($value);
                $flag = 1;
            }
            $url = "http://web.wasun.cn/asmx/smsservice.aspx?" . $params; //提交的url地址

            $con = substr(file_get_contents($url), 0, 1);  //获取信息发送后的状态

            if ($con == '0') {
                // 信息发送成功,修改订单处理状态
                Db::name('order')
                    ->where('id', $v)
                    ->setField('dispose_status', 'no_collection');
                $success = $success + 1;
            } else {
                $error = $error + 1;
                $error_id[] = $v;
            }
        }
        if (count($error_id) === 0) {
            $msg = '成功发送：' . $success . '条。失败发送' . $error . "条。";
        } else {
            $temp = implode(',', $error_id);
            $msg = '成功发送：' . $success . '条。失败发送' . $error . "条。失败的订单ID为：" . $temp . "。";
        }
        return ajax_return_adv($msg);
    }

    /**
     * 发送短信
     * @return mixed
     */
    public function send_msg()
    {
        $id = input('id');

        $order = Db::name("order")->where('id', $id)->find();
        $url = get_host() . "/traveller/order_traveller/index?id={$order['order_id']}";
        $mobile = $order['booking_people_phone'];
        if (!$order['booking_people_phone'] || !$order['order_id']) {
            return ajax_return_error("手机号码或者平台订单id为空");
        }
        $argv = array(
            'name' => '18694047848',     //必填参数。用户账号
            'pwd' => '9FA6EB4D075A98F84F896CF0D451',     //必填参数。（web平台：基本资料中的接口密码）
            'content' => '请填写你的旅客信息：' . $url . '，请勿将链接提供给他人。',   //必填参数。发送内容（1-500 个汉字）UTF-8编码
            'mobile' => $mobile,   //必填参数。手机号码。多个以英文逗号隔开
            'stime' => '',   //可选参数。发送时间，填写时已填写的时间发送，不填时为当前时间发送
            'sign' => '青海精灵国旅',    //必填参数。用户签名。
            'type' => 'pt',  //必填参数。固定值 pt
            'extno' => ''    //可选参数，扩展码，用户定义扩展码，只能为数字
        );

        //构造要post的字符串
        $flag = 0;
        $params = '';//要post的数据
        foreach ($argv as $key => $value) {
            if ($flag != 0) {
                $params .= "&";
                $flag = 1;
            }
            $params .= $key . "=";
            $params .= urlencode($value);// urlencode($value);
            $flag = 1;
        }
        $url = "http://web.wasun.cn/asmx/smsservice.aspx?" . $params; //提交的url地址

        $con = substr(file_get_contents($url), 0, 1);  //获取信息发送后的状态

        if ($con == '0') {
            // 信息发送成功,修改订单处理状态
            Db::name('order')
                ->where('id', $id)
                ->setField('dispose_status', 'no_collection');
            return ajax_return_adv("已发送");
        } else {
            return ajax_return_error('发送失败');
        }

    }

    /**
     * 确定是否开发票
     * @param int $order_id
     * @param int $invoice
     * @url /admin/order/invoice
     * @author 邓汉炜
     */
    public function invoice()
    {
        $data = input();
        //验证数据
        $rule = [
            'order_id' => 'require',
            'invoice' => 'require'
        ];
        $msg = [
            'order_id.require' => '订单id不能为空',
            'invoice.require' => '开发票字段值不能为空',
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($data);
        if (!$result) {
            return ajax_return_adv_error($validate->getError());
        }
        //更新开发票字段
        $invoiceResult = Db::name('order')->where('id', $data['order_id'])->update(['invoice' => $data['invoice']]);
        if ($invoiceResult) {
            return ajax_return_adv('确认开发票成功');
        } else {
            return ajax_return_adv_error('开具发票失败');
        }
    }

    /**
     * 添加数据到控房表
     */
    public static function addAccommodation($order_id)
    {
        $str = '';
        // 根据订单id查找所有订单旅客
        $data = Db::name('order_traveler')->where('oid', $order_id)->select();
        if (empty($order_id) || empty($data)) {
            $str = '缺少订单id或者没有订单旅客数据';
            return $str;
        }
        $dataArr = [];
        foreach ($data as $index => $datum) {
            if ($datum['isaccommodation'] == '包含住宿') {
                $dataArr[] = [
                    'order_id' => $datum['oid'],
                    'order_traveler_id' => $datum['id'],
                    'create_time' => time(),
                    'is_accommodation' => 1,
                    'remark' => $datum['accommodation'],
                ];
            }
        }
        if (!empty($dataArr)) {
            $add = Db::name('accommodation')->strict(false)->insertAll($dataArr);
            if ($add) {
                $str = '添加住房旅客成功';
                return $str;
            } else {
                $str = '添加住房旅客失败';
                return $str;
            }
        } else {
            $str = '没有日安家任何住房记录';
            return $str;
        }
    }

    /**
     * 获取旅游路线
     * @author 邓汉炜
     * @urrl /admin/order/getRoad
     */
    public function getRoad(Request $request)
    {
        if ($request->isPost()) {
            $postData = $request->post();
            if (!$postData['id']) {
                return ajax_return_adv_error('未选择路线');
            }
            if (!$postData['start']) {
                return ajax_return_adv_error('未选择开始时间');
            }
            $route = Db::name('route')->where('id', $postData['id'])->find();
            if (!$route) {
                return ajax_return_adv_error('旅游路线不存在!');
            } elseif (!$route['day']) {
                return ajax_return_adv_error('旅游路线还没有设置天数');
            }
            $date = [$postData['start']];
//            $tian =
            for ($i = 1; $i < $route['day']; $i++) {
                array_push($date, date("Y-m-d", strtotime("+{$i} day", strtotime("{$postData['start']}"))));//添加的
            }
            $day = '';
            if (!empty($date)) {
                $day = array_pop($date);
            } else {
                $day = 0;
            }
            $ret['day'] = $day;

            return ajax_return_adv('获取成功', '', '', '', '', $ret);
        } else {
            return ajax_return_adv_error('非法请求');
        }
    }

    /**
     * 设置好评
     * @return mixed
     */
    public function good_evaluate()
    {
        $order_id = input('order_id');

        Db::name('order')
            ->where('order_id', $order_id)
            ->setField('is_review', 1);

        return ajax_return_adv('设置成功');
    }

    /**
     * 设置差评
     * @return mixed
     */
    public function bab_evaluate()
    {
        $order_id = input('order_id');

        Db::name('order')
            ->where('order_id', $order_id)
            ->setField('is_review', 2);

        return ajax_return_adv('设置成功');
    }

    /**
     * 获取评价列表
     * @return mixed
     */
    public function evaluate()
    {
        $data = input();

        if (isset($data['is_review']) && $data['is_review'] == 3) {
            $map['is_review'] = ['in', '1,2'];
            $map['order_status'] = ['=', 'finish'];
        } else {
            $map['is_review'] = ['=', (int)$data['is_review']];
        }

        if ($data['sales_name']) {
            $map['sales_name'] = ['like', "%{$data['sales_name']}%"];
        }

        if ($data['platform']) {
            $map['platform'] = ['=', $data['platform']];
        }

        if ($data['booking_people_name']) {
            $map['booking_people_name'] = ['like', "%{$data['booking_people_name']}%"];
        }

        if ($data['booking_people_phone']) {
            $map['booking_people_phone'] = ['like', "%{$data['booking_people_phone']}%"];
        }

        if ($data['order_id']) {
            $map['order_id'] = ['like', "%{$data['order_id']}%"];
        }

        $listRows = $this->request->param('numPerPage') ? 20 : Config::get("paginate.list_rows");

        $list = Db::name('order')
            ->order('id desc')
            ->where($map)
            ->paginate($listRows, false, ['query' => $this->request->get()]);

        $new_list = $list->toArray()['data'];

        foreach ($new_list as $k => $v) {
            if ($v['is_review'] === 0) {
                $new_list[$k]['evaluate'] = null;
            } else {
                $new_list[$k]['evaluate'] = Db::name('order')
                    ->alias('o')
                    ->join('tp_order_evaluate oe', 'o.order_id=oe.oid', 'left')
                    ->field('oe.*')
                    ->where('o.order_id', $v['order_id'])
                    ->find();

                $new_list[$k]['route'] = Db::name('route')
                    ->where('id', $v['route_id'])
                    ->value('title');

                $new_list[$k]['evaluate']['src'] = explode(',', $new_list[$k]['evaluate']['img_src']);
            }
        }
//        halt($new_list);

        $platform = Db::name('platform')->select();
        $this->view->assign('is_review', $data['is_review']);
        $this->view->assign('platform', $platform);
        $this->view->assign('list', $new_list);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        return $this->view->fetch();
    }

    /**
     * 添加评价
     * @return mixed
     */
    public function add_evaluate()
    {
        $data = input();
        if ($this->request->isAjax()) {

            $img_src = [];

            if(isset($data['head_img'])){
                foreach ($data['head_img'] as $k => $v) {
                    $file = Db::name('upload_file')
                        ->where('id', $v)
                        ->find();

                    $img_src[] = $file['domain'] . $file['url'];
                }
            }

            $order_info = Db::name('order')
                ->where('order_id', $data['order_id'])
                ->find();

            $order_evaluate_result = Db::name('order_evaluate')
                ->insert([
                    'oid' => $data['order_id'],
                    'platform' => $data['platform'],
                    'user_name' => $order_info['booking_people_name'],
                    'comment' => $data['comment'],
                    'shop_name' => '花儿户外',
                    'comment_status' => $data['is_review'],
                    'img_src' => implode(',', $img_src),
                    'create_time' => time()
                ]);

            $order_result = Db::name('order')
                ->where('order_id', $data['order_id'])
                ->setField('is_review', $data['is_review']);

            if ($order_evaluate_result && $order_result) {
                return ajax_return_adv('评价成功!');
            } else {
                ajax_return_adv_error('评价失败,请重试!');
            }
        } else {
            //获取平台列表
            $platform = Db::name('platform')->select();
            $this->view->assign('platform', $platform);
            return $this->view->fetch();
        }
    }


    /**
     *  同步订单
     * @url /admin/order/syncOnlineOrder
     */
    public function syncOnlineOrder()
    {
        $data = input();
        $id = $data['id'];
        if (!empty($id)) {
            // 根据传过来的订单是马蜂窝,还是飞猪的,或者是手动添加的
            $orderData = Db::name('order')->where('id', 'in', $id)
                ->field('id,order_id,platform')
                ->select();
            if (empty($orderData)) {
                return ajax_return_adv_error('订单不存在');
            }
            $backEnd = [];// 后台手动添加的订单
            $mfwOrder = []; // 马蜂窝同步的订单
            $flyPigOrder = []; // 飞猪同步订单
            foreach ($orderData as $index => $orderDatum) {
                switch ($orderDatum['platform']) {
                    case 'mfw':
                        if (substr($orderDatum['order_id'], 0, 1) != 'h' && !(preg_match('/[\x{4e00}-\x{9fa5}]/u', $orderDatum['order_id']) > 0) && strlen($orderDatum['order_id']) > 10) {
                            $mfwOrder[] = $orderDatum['order_id'];
                        } else {
                            $backEnd[] = $orderDatum['id']; // 不是同步的,后台手动的
                        }
                        break;
                    case 'Fliggy': // 飞猪订单
                        if (substr($orderDatum['order_id'], 0, 1) != 'h' && !(preg_match('/[\x{4e00}-\x{9fa5}]/u', $orderDatum['order_id']) > 0) && strlen($orderDatum['order_id']) > 10) {
                            $flyPigOrder[] = $orderDatum['order_id'];
                        } else {
                            $backEnd[] = $orderDatum['id'];
                        }
                        break;
                    default:
                        $backEnd[] = $orderDatum['id'];
                }
            }
            // 同步马蜂窝订单
            if (!empty($mfwOrder)) {
//                halt($mfwOrder);
                foreach ($mfwOrder as $index8 => $item8) {
                    $api = new \app\common\model\MfwApi();
                    $_data['order_id']=$item8;
                    $api->save_syn_order($_data);
//                    \app\common\model\OrderCheck::task($item8);
                }
                return ajax_return_adv('已同步');
            }
            return ajax_return_adv_error('没有订单可以更新');
        } else {
            return ajax_return_adv_error('请选择订单', '', '', '', '', '');
        }
    }


}
